// 网上很多的 crc16 库不行。此处要注意
export function crc16(message) {
  const table = [];
  const polynom = 33800
  const initValue = 0
  const bytes = 2
  for (j = 0; j < 256; ++j) {
      b = j;
      for (k = 0; k < 8; ++k) {
          b = b & 1 ? polynom ^ (b >>> 1) : b >>> 1
      }
      table[j] = b >>> 0
  }
  var notString = typeof message !== "string";
  message = new Uint8Array(message)
  var crc = initValue,
  code, i, length = message.length
  var HEX_CHARS = "0123456789abcdef".split("");
  if (notString) {
      for (i = 0; i < length; ++i) {
          crc = table[(crc ^ message[i]) & 255] ^ (crc >>> 8)
      }
  } else {
      for (i = 0; i < length; ++i) {
          code = message.charCodeAt(i);
          if (code < 128) {
              crc = table[(crc ^ code) & 255] ^ (crc >>> 8)
          } else {
              if (code < 2048) {
                  crc = table[(crc ^ (192 | (code >> 6))) & 255] ^ (crc >>> 8);
                  crc = table[(crc ^ (128 | (code & 63))) & 255] ^ (crc >>> 8)
              } else {
                  if (code < 55296 || code >= 57344) {
                      crc = table[(crc ^ (224 | (code >> 12))) & 255] ^ (crc >>> 8);
                      crc = table[(crc ^ (128 | ((code >> 6) & 63))) & 255] ^ (crc >>> 8);
                      crc = table[(crc ^ (128 | (code & 63))) & 255] ^ (crc >>> 8)
                  } else {
                      code = 65536 + (((code & 1023) << 10) | (message.charCodeAt(++i) & 1023));
                      crc = table[(crc ^ (240 | (code >> 18))) & 255] ^ (crc >>> 8);
                      crc = table[(crc ^ (128 | ((code >> 12) & 63))) & 255] ^ (crc >>> 8);
                      crc = table[(crc ^ (128 | ((code >> 6) & 63))) & 255] ^ (crc >>> 8);
                      crc = table[(crc ^ (128 | (code & 63))) & 255] ^ (crc >>> 8)
                  }
              }
          }
      }
  }
  crc ^= initValue;
  var hex = "";
  if (bytes > 2) {
      hex += HEX_CHARS[(crc >> 28) & 15] + HEX_CHARS[(crc >> 24) & 15] + HEX_CHARS[(crc >> 20) & 15] + HEX_CHARS[(crc >> 16) & 15]
  }
  hex += HEX_CHARS[(crc >> 12) & 15] + HEX_CHARS[(crc >> 8) & 15] + HEX_CHARS[(crc >> 4) & 15] + HEX_CHARS[crc & 15];
  return hex
}